#!/usr/bin/env python
#-*- coding:utf8 -*-
"""
Function attributes:
* load: boolean. Optional. If False the function will not load.
* name: string. Optional.
* priority: string. Optional. Three values are available: "high", "medium" or "low",
  default value: "medium".
* thread: boolean. Optional. If True, function will work by starting a thread.
* rule: string or regexp object. Required.
* aliases: list of string or regexp objects. Optional.
* fullmsg: boolean. Optional. If True, pattern is searched on whole message, else
  pattern is a command, the message must begin with a sign.

* access
* evttypes: must be tuple
* skip_sentinel: skip _sentinel instance
* limit
* channels
* url
* showas
"""
import re
from util.pywikilib import Site, Page, WikiLink
from util import sitematrix
from core.optimizers import fmt
field = "votes"

def elections(bot, evt, cmd):
	#implementat el 21.03.09
	opts=getArgs(args, ['n', 'c', 'f', 'e', 'r', 'd', 'del', 'show', 'all', 'h'])
	nom=opts['n']		#short name, needed
	datac=opts['c']	#date of proposal, needed.
	dataf=opts['f']	#first date for valid edits, default: 90 (days before)
	edits=opts['e']	#number of edits, default: 100
	registre=opts['r']	#date of user's registration, default: 30 (days)
	default=opts['d']	#make item as default
	delete=opts['del']	#delete an item
	show=opts['show']	#show an item with details
	all=opts['all']	#show all items (only names)
	help=opts['h'] or (opts.has_key('help') and opts['help'])

	if help:
		c.privmsg(canal, "http://ca.wikipedia.org/wiki/Usuari:PasqualBot/IRC/ordres_geni#.40votacions")
		return

	values=[]
	for vl in opts:
		if opts[vl]:
			values.append(vl)
	if not values: show = args.strip()

	if all:
		items=[]
		for v in dVotacions:
			items.append(v[0])
		items=", ".join(items)
		msg= u"llista de votacions predefinides: %s." % items
		c.privmsg(canal, msg.encode("utf-8"))
		return

	if show:
		for v in dVotacions:
			if show == v[0]:
				datac=time.strftime("%d-%m-%Y", time.localtime(v[1][0]))
				dataf=time.strftime("%d-%m-%Y", time.localtime(v[1][1]))
				edits=v[1][2]
				reg=v[1][3]
				created=time.strftime("%d-%m-%Y", time.localtime(v[1][4]))
				auth=v[1][5]
				msg=u"%s: data inici: %s, data primera contrib.: %s, contrib. mín.: %s, mín. dies registrat: %s. (Creat per %s, el %s.)" \
					% (show, datac, dataf, edits, reg, auth, created)
				c.privmsg(canal, msg.encode("utf-8"))
		return

	if delete:
		for v in dVotacions:
			if delete == v[0]:
				dVotacions.remove(v)
				desaVotacions()
				c.privmsg(canal, "dades esborrades.")
				break
		return

	if default:
		for v in dVotacions:
			if nom == v[0]:
				n=v
				dVotacions.remove(v)
				dVotacions.insert(0, n)
				desaVotacions()
				msg=u"Ara %s s la votaci per defecte." % dVotacions[0][0]
				c.privmsg(canal, msg.encode("utf-8"))
				break
		return

	datac=re.search(r"(\d{2})-(\d{2})-(\d{4})",datac)
	if datac:
		datac=datac.groups()
		datac=datetime.datetime(int(datac[2]), int(datac[1]),int(datac[0]))
	if not dataf:
		dataf=datac-datetime.timedelta(days=90)
	else:
		dataf=re.search(r"(\d{2})-(\d{2})-(\d{4})",dataf)
		if dataf:
			dataf=dataf.groups()
			dataf=datetime.datetime(int(dataf[2]), int(dataf[1]),int(dataf[0]))
	if not edits:
		edits="100"
	if not registre:
		registre=30
	dVotacions.append((nom,[time.mktime(datac.timetuple()), time.mktime(dataf.timetuple()), edits, registre, time.time(), nick]))
	desaVotacions()

	votacio=dVotacions[-1]
	d1=time.strftime("%d-%m-%Y", time.localtime(votacio[1][0]))
	d2=time.strftime("%d-%m-%Y", time.localtime(votacio[1][1]))
	c.privmsg(canal, "%s desat amb les dates: %s (inici), %s (data llimit)" % (nom, d1, d2 ))
elections.rule = ["votacions"]
elections.wherelang = "ca"

def votability(bot, evt, cmd):
	#implementat el 21.03.09
	opts=getArgs(args, ['u','c','f','e','v','r'])
	#print opts
	user=opts['u']
	start=opts['c']
	end=opts['f']
	edits=opts['e']	#default: 100
	registre=opts['r']	#default: 30 (days)
	votacio=nom_votacio=opts['v']
	ara= opts.has_key('ara') or opts.has_key('now')
	if ara: opts['c'] = start = time.strftime("%d-%m-%Y", time.localtime(time.time()+86400))

	if not user:
		user = args.split(" -")[0].strip()
		if not user: return

	if votacio:
		for v in dVotacions:
			if v[0] == votacio:
				 votacio=dVotacions[dVotacions.index(v)]
			else:
				votacio=dVotacions[0]
	else:
		votacio=dVotacions[0]
		nom_votacio=votacio[0]


	costumized= opts['c'] != False
	if costumized:
		if start:
			start=parseDate(start)
		else:
			return

		if not end:
			end=start-datetime.timedelta(days=90)
		else:
			end=parseDate(end)
		start=start.timetuple()
		end=end.timetuple()
		start=time.mktime(start)
		end=time.mktime(end)

		if not edits:edits="100"
		if registre and registre.isdigit():
			registre = 60*60*24*int(registre)
		else: registre = 60*60*24*30

	elif votacio:
		start=votacio[1][0]
		end=votacio[1][1]
		edits=votacio[1][2]
		registre=votacio[1][3]
	if start and end:
		start=time.strftime("%Y%m%d000000", time.localtime(start))
		end=time.strftime("%Y%m%d000000", time.localtime(end))
	msg= u"la votació seleccionada és: "+nom_votacio
	#c.privmsg(canal, msg.encode("utf-8"))

	#get registration date
	apiurl = 'http://ca.wikipedia.org/w/api.php?action=query&list=allusers&aufrom=%s&aulimit=1&format=xmlfm&auprop=registration&auwitheditsonly' % trurl(user)
	apidata=net.pageText(apiurl).decode("utf-8")
	reg=re.search('<span style="color:blue;">&lt;u name=&quot;(?P<user>.*?)&quot; registration=&quot;(?P<date>.*?)&quot; /&gt;</span>', apidata)

	if reg and reg.groupdict()["date"]:
		date= parseAPIts(reg.group('date') or "2005-11-01T00:00:00Z")
		diff = deltatime(datetime.datetime.now(), date)
		days = diff.days
		years = diff.years
		months = diff.months
		usr= reg.group('user')
		if usr != user:
			c.privmsg(canal, "Usuari erroni, inexistent o sense edicions!")
			return
		if (years== 0 and months == 0 and days >= registre) or months >= 1 or years > 1:
			pass
		else:
			c.privmsg(canal, "L'usuari es va registrar fa menys de 30 dies. [%s y, %i m, %i d]" % (years, months, days))
			return

	#get user contribs and count they
	apiurl="http://ca.wikipedia.org/w/api.php?action=query&list=usercontribs&ucnamespace=0&ucstart=%(start)s&ucend=%(end)s&uclimit=%(limit)s&ucprop=title|timestamp&ucuser=%(user)s" % {"start": start, "end":end, "limit": edits, "user": trurl(user)}
	c.notice("coet", "%s&format=jsonfm" % apiurl)
	#print apiurl
	apidata=net.pageText(apiurl).decode("utf-8")

	data = re.findall('<span style="color:blue;">&lt;item user=&quot;.*?&quot; ns=&quot;\d+&quot; title=&quot;.*?&quot; timestamp=&quot;(.*?)T.*?Z&quot; /&gt;</span>', apidata)
	numberOfEdits=len(data)
	if numberOfEdits>=int(edits):
		c.privmsg(canal, "l'usuari pot votar. Tenia %i abans edicions en el temps seleccionat abans d'iniciar el procés de votació." % numberOfEdits)
	else:
		c.privmsg(canal, "l'usuari NO pot votar. Només tenia %i edicions en el temps seleccionat abans d'iniciar el procés de votació."% numberOfEdits)
	wikiurl = "http://ca.wikipedia.org/wiki/Especial:Contribucions/%(user)s?offset=%(start)s&limit=%(limit)s&namespace=0" % {"start": start, "limit": edits, "user": trurl(user)}
	c.privmsg(canal, wikiurl)
votability.rule = "canvote"
votability.chanlang = {"ca": "potvotar"}
